package com.dal.constant;

import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.error.LoginErrorCode;

import com.sojoys.artifact.exception.AbstractLogicModelException;
import com.sojoys.artifact.tools.ToolError;

/**
 * Created by fxf on 2017/6/22.
 */
public class Lock {


    public static final byte[] dump = new byte[]{};

    public static final ConcurrentHashMap<String,byte[]> Locks = new ConcurrentHashMap<String,byte[]>();

    private static Logger logger = LogManager.getLogger(Lock.class);

    public static boolean lock(String lockKey) throws AbstractLogicModelException {
        if(lockKey == null){
            logger.error("锁定失败"  + lockKey);
            return false;
        }

        if(Locks.putIfAbsent(lockKey, dump) != null){
            logger.error("锁定失败"  + lockKey);
            throw ToolError.newLogicError(LoginErrorCode.ACCOUNT_DEALING);
        }
        return true;
    }


    public static void unlock(String lockKey){
        if(lockKey == null){
            logger.error("解锁失败"  + lockKey);
            return;
        }
        synchronized (Locks) {
            Locks.remove(lockKey);
        }
    }


}
